<template>
  <!-- 模态框 -->
  <div class="modal">
    <!-- 不使用嵌套的方式布局，避免后期事件冒泡的问题 -->
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginMedal(false)"></div>
    <!-- 登陆盒子 -->
    <div class="loginBox">
      <span class="close" @click="changeIsShowLoginMedal(false)"></span>
      <!-- 导航区域 -->
      <section class="nav">
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true"
          >手机号登录</a
        >
        |
        <a href="#" :class="{ active: !isShowPhone }" @click="winShow"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容部分 -->
      <div class="content">
        <!-- 手机号部分 -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
              class="ipt"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgs"
              :accuracy="9999"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机验证码"
              v-model="code"
              class="ipt"
            />
            <!-- 连续点击会触发getCode-会创建多个定时器，造成递减混乱 -->
            <button class="codelogin" v-show="!isShowCount" @click="getCode">
              获取验证码
            </button>
            <button class="codelogin" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信部分 -->
        <div class="qrLogin" id="weixin" v-show="!isShowPhone"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { SendSMSAPI, phoneReginAPI, BinddingApi } from "@/request/api";
import { validatePhoneNumber } from "@/utils/index";

export default {
  name: "Jifen1Login",

  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      imgs: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
      ],
      phoneNumber: "",
      count: 59,
      // 是否显示倒计时
      isShowCount: false,
      code: "",
    };
  },

  mounted() {},

  methods: {
    ...mapMutations({
      changeIsShowLoginMedal: "showModal/changeIsShowLoginModal",
      isLoginedShow: "loginStatus/isLoginedShow",
      // changeIsShowLoginToast: "showToast/changeIsShowLoginToast",
    }),
    ...mapActions({
      asyncChangeIsShowLoginToast: "showToast/asyncChangeIsShowLoginToast",
      asyncuserInfoLogin: "userinfo/asyncuserInfoLogin",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 倒计时
    daojishi() {
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 59;
          // 停止 clear
          clearInterval(timer);
          this.isShowCount = false;
        }
      }, 1000);
    },

    toVerfy() {
      // 1.判断手机号是否正确，如果不正确 提示
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号");
        this.asyncChangeIsShowLoginToast({
          isShow: true,
          Msg: "请输入正确的手机号",
          Type: "success",
        });
        // setTimeout(() => {
        //   this.changeIsShowLoginToast({
        //     isShow: false,
        //   });
        // }, 1000);
        return;
      }
      // 2.滑块验证码不正确提示
      // 如果当前msg 是 '再试一次' or '向右滑块' 提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请滑动滑块");
        this.asyncChangeIsShowLoginToast({
          isShow: true,
          Msg: "请滑块",
          Type: "success",
        });
        return;
      }

      // 函数默认返回 undefined
      return true;
    },

    //获取验证码
    async getCode() {
      let flag = this.toVerfy();
      console.log(flag);
      if (!flag) return;
      this.isShowCount = true;
      // 3.获取验证码 -- 60s 倒计时功能

      // 发送验证码
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      console.log(res);
      // if (res.data.code == 0) {
      //   alert("发送成功");
      //   this.daojishi();
      // }
      if (!res) return;
      alert("发送成功");
      this.daojishi();
    },

    //登录
    async submitFn() {
      // 1. 手机号不正确提示
      // 2. 滑块不正确提示
      if (!this.toVerfy()) return;
      // 3. 短音验证码不正确提示
      if (this.code.trim() == "") {
        alert("请输入验证码");
        return;
      }

      // 4. 发送登录请求 分两种情况，有uuid 关联微信，没有就普通的手机号登录
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BinddingApi({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await phoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      alert("验证成功");
      // 1.提示
      // 2.存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.关闭模态框
      this.changeIsShowLoginMedal(false);
      // 4.topbar中登录状态的切换 (修改vuex中的isLo)
      this.isLoginedShow(true);

      // 绑定1
      uuid && this.$router.push(this.$route.path);

      // 绑定2
      localStorage.removeItem("uuid");

      //获取用户信息 更新vuex的信息
      this.asyncuserInfoLogin();
    },

    //微信
    winShow() {
      this.isShowPhone = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  height: 100%;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  .mask {
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.226);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("@/assets/img/login-box-bg.png");
    .close {
      position: absolute;
      width: 23px;
      height: 23px;
      top: 10px;
      right: 56px;
      background: url("@/assets/img/close.png") no-repeat;
      cursor: pointer;
    }
    .nav {
      text-align: center;
      padding-top: 50px;
      a {
        text-decoration: none;
        color: gray;
        &.active {
          color: #000;
        }
      }
    }
    .content {
      width: 355px;
      height: 300px;
      margin: 10px auto 0;
    }
  }
  .phoneLogin {
    .row {
      display: flex;
      margin-bottom: 20px;
      .ipt {
        flex: 1;
        height: 50px;
        text-indent: 1em;
        outline: none;
      }
      button {
        cursor: pointer;
      }
      .codelogin {
        border: none;
        width: 85px;
        background: #0a328e;
        color: #fff;
        margin-left: 10px;
      }

      .btnlogin {
        border: none;
        background: #0a328e;
        color: #fff;
        width: 100%;
        height: 50px;
      }
    }
  }
  .qrLogin {
    text-align: center;
  }

  //滑块验证码
  /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
      position: absolute;
      left: 0;
      top: -120px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -120px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }

    .slide-verify-slider-mask[data-v-2921b679] {
      height: 48px;
    }
    .slide-verify-slider[data-v-2921b679] {
      height: 50px;
      line-height: 50px;
      margin-top: 0;
    }
    .slide-verify-slider-mask-item[data-v-2921b679] {
      height: 50px;
      border: 0;
    }
    .slide-verify-slider-mask-item-icon[data-v-2921b679] {
      top: 20px;
    }
  }
}
</style>